package com.atguigu.stack;

import java.util.Scanner;

/**
 * 使用数组模拟栈的实现
 *
 * @author WangJX
 * @version 1.0
 * @date 2019/9/28 22:28
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        Scanner scanner = new Scanner(System.in);
        boolean loob = true;
        while (loob) {
            System.out.println("1：添加数据");
            System.out.println("2：取出数据");
            System.out.println("3：显示数据");
            System.out.println("4：退出");
            int key = scanner.nextInt();
            switch (key){
                case 1:
                    System.out.println("请输入要添加数据：");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case 2:
                    try {
                        int pop = stack.pop();
                        System.out.println(pop);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 3:
                    stack.show();
                    break;
                case 4:
                    loob = false;
                    break;
                default:
                    break;
            }
        }
    }

}

class ArrayStack {
    int top = -1;   //指向栈的最顶端
    int[] stack;    //存储数据
    int maxSize;

    public ArrayStack(int size) {
        this.maxSize = size;
        this.stack = new int[maxSize];
    }

    /**
     * 判断栈是否满
     *
     * @return
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 判断栈是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 添加数据
     *
     * @param value
     */
    public void push(int value) {
        if (isFull()) {
            throw new RuntimeException("栈已满");
        }
        top++;
        stack[top] = value;
    }

    /**
     * 取数据
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 显示栈数据
     */
    public void show() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d] = %d\n", i, stack[i]);
        }
    }
}

